package com.cash.loan.common.filter;

import com.cash.loan.common.util.RedisUtil;
import com.cash.loan.core.util.IpUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * @author yangbo
 * @date 2019-11-28 14:41
 */
@Component
public class IpDenyFilter extends OncePerRequestFilter {

    private static final String DENY_IP_SET = "deny_ip_set";

    private static final String SET_PREFIX = "_set:";

    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String requestIp = IpUtils.getIpAddr(request);
        if(redisUtil.existKey(SET_PREFIX + DENY_IP_SET)) {
            Set<String> denyIpSet = redisUtil.getSet(DENY_IP_SET);
            if(denyIpSet != null && denyIpSet.contains(requestIp)) {
                return;
            }
        }
        filterChain.doFilter(request,response);
    }

    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }
}
